<?php
namespace app\admin\controller;
header("content-type:text/html;charset=utf-8");
use app\admin\controller\Base;
use app\admin\model\Admin;
use app\admin\model\Apply;
use app\admin\model\Applytype;
use app\admin\model\Classtype;
use app\admin\model\Course;
use app\admin\model\Myclass;
use app\admin\model\Naturetype;
use app\admin\model\Money as Moneys;
use app\admin\model\User;
use app\admin\model\Usertype;
use think\App;
use think\Db;
use think\Request;
use think\File;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class  Money extends Base
{

  
  //生成图片
  public function create_advice(Request $request)
  {
    header('content-type:image/png');
    $user = $this->user_info();
    //查询缴费信息和用户信息
    $money = Moneys::get($request->get("id"));
//    $money = Moneys::get(4);
    $user = User::get($money['userid']);
    $apply = Apply::field("major")->where("userid",$money['userid'])->find();

    $sex = $user['sex'] == 1 ? "男" : "女";
    $money_xf = empty($money['money_xf']) ? "0.00" : $money['money_xf'];
    $money_xzf = empty($money['money_xzf']) ? "0.00" : $money['money_xzf'];
    $money_zsf = empty($money['money_zsf']) ? "0.00" : $money['money_zsf'];
    $money_number = array_sum([$money_xf,$money_xzf,$money_zsf,500]);
    $money_sum = number_format($money_number,2);
    $setting = $this->getAllSetting();

    //创建图片开始
    $width =2480;
    $height =1267;
    $img =imagecreatetruecolor($width,$height);
    $textcolor = imagecolorallocate($img,0,0,0);
    $bg = imagecreatefrompng(ROOT_PATH."/public/static/admin/img/jfpz.png");
    imagecopy($img,$bg,0,0,0,0,$width, $height);
    //填写内容
    imagettftext($img, 30, 0, 320, 234, $textcolor, ROOT_PATH."/public/static/admin/fonts/simsun.ttc", $money['pay_number']);
    imagettftext($img, 30, 0, 460, 288, $textcolor, ROOT_PATH."/public/static/admin/fonts/simsun.ttc", date('Y 年 m 月 d 日',$money['create_times']));
    imagettftext($img, 30, 0, 670, 356, $textcolor, ROOT_PATH."/public/static/admin/fonts/simsun.ttc", $user['name']);
    imagettftext($img, 30, 0, 670, 436, $textcolor, ROOT_PATH."/public/static/admin/fonts/simsun.ttc", $sex);
    imagettftext($img, 30, 0, 670, 516, $textcolor, ROOT_PATH."/public/static/admin/fonts/simsun.ttc", $user['idcard']);
    imagettftext($img, 30, 0, 670, 596, $textcolor, ROOT_PATH."/public/static/admin/fonts/simsun.ttc", $apply['major']);
    imagettftext($img, 30, 0, 460, 676, $textcolor, ROOT_PATH."/public/static/admin/fonts/simsun.ttc", $money['pay_type']);
    imagettftext($img, 30, 0, 2000, 670, $textcolor, ROOT_PATH."/public/static/admin/fonts/simsun.ttc", $money_sum."元");
    imagettftext($img, 30, 0, 1550, 675, $textcolor, ROOT_PATH."/public/static/admin/fonts/simsun.ttc",$this->num_to_upper($money_number));
    imagettftext($img, 30, 0, 1230, 805, $textcolor, ROOT_PATH."/public/static/admin/fonts/simsun.ttc",$setting['money_xf']);
    imagettftext($img, 30, 0, 1250, 865, $textcolor, ROOT_PATH."/public/static/admin/fonts/simsun.ttc",$setting['money_zsf']);
    imagettftext($img, 30, 0, 1280, 925, $textcolor, ROOT_PATH."/public/static/admin/fonts/simsun.ttc",$setting['money_xzf']);
    imagettftext($img, 30, 0, 1630, 805, $textcolor, ROOT_PATH."/public/static/admin/fonts/simsun.ttc","预报名费500元，实收".$money['money_xf']."元");
    imagettftext($img, 30, 0, 1250, 1035, $textcolor, ROOT_PATH."/public/static/admin/fonts/simsun.ttc",$money['comment']);

    imagepng($img);
    imagedestroy($img);
    exit();
  }
  //将年月日转为汉字
  public function big_number($number){
    $str = "";
    $len = strlen($number);
    if($len == 4) {
      for ($i = 0; $i < $len; $i++) {
        switch (substr($number, $i, 1)) {
          case 1 :
            $str .= "一";
            break;
          case 2 :
            $str .= "二";
            break;
          case 3 :
            $str .= "三";
            break;
          case 4 :
            $str .= "四";
            break;
          case 5 :
            $str .= "五";
            break;
          case 6 :
            $str .= "六";
            break;
          case 7 :
            $str .= "七";
            break;
          case 8 :
            $str .= "八";
            break;
          case 9 :
            $str .= "九";
            break;
          case 0 :
            $str .= "〇";
            break;
        }
      }
    }else if($len == 2 ){
      switch (substr($number, 0, 1)) {
        case 1 :
          $str .= "十";
          break;
        case 2 :
          $str .= "二十";
          break;
        case 3 :
          $str .= "三十";
          break;
      }
      switch (substr($number, 1, 1)) {
        case 1 :
          $str .= "一";
          break;
        case 2 :
          $str .= "二";
          break;
        case 3 :
          $str .= "三";
          break;
        case 4 :
          $str .= "四";
          break;
        case 5 :
          $str .= "五";
          break;
        case 6 :
          $str .= "六";
          break;
        case 7 :
          $str .= "七";
          break;
        case 8 :
          $str .= "八";
          break;
        case 9 :
          $str .= "九";
          break;
        case 0 :
          $str .= "";
          break;
      }
    }else if($len == 1 ){
      switch ($number) {
        case 1 :
          $str .= "一";
          break;
        case 2 :
          $str .= "二";
          break;
        case 3 :
          $str .= "三";
          break;
        case 4 :
          $str .= "四";
          break;
        case 5 :
          $str .= "五";
          break;
        case 6 :
          $str .= "六";
          break;
        case 7 :
          $str .= "七";
          break;
        case 8 :
          $str .= "八";
          break;
        case 9 :
          $str .= "九";
          break;
      }
    }
    return $str;
  }
  //人民币转为大写
  public function num_to_upper($num)
  {
    $d = array('零','壹','贰','叁','肆','伍','陆','柒','捌','玖');
    $e = array('元','拾','佰','仟','万','拾万','佰万','仟万','亿','拾亿','佰亿','仟亿','万亿');
    $p = array('分','角');
    $zheng='整'; //追加"整"字
    $final = array(); //结果
    $inwan=0; //是否有万
    $inyi=0; //是否有亿
    $len_pointdigit=0; //小数点后长度
    $y=0;
    if($c = strpos($num, '.')) {    //有小数点,$c为小数点前有几位数
      $len_pointdigit = strlen($num)-strpos($num, '.')-1; // 判断小数点后有几位数
      if($c>13) { //简单的错误处理
        echo "数额太大,已经超出万亿.";
        die();
      } elseif($len_pointdigit>2) {   //$len_pointdigit小数点后有几位
        echo "小数点后只支持2位.";
        die();
      }
    } else {    //无小数点
      $c = strlen($num);
      $zheng = '整';
    }
    for($i=0;$i<$c;$i++) {  //处理整数部分
      $bit_num = substr($num, $i, 1); //逐字读取 左->右
      if($bit_num!=0 || substr($num, $i+1, 1)!=0) //当前是零 下一位还是零的话 就不显示
        @$low2chinses = $low2chinses.$d[$bit_num];
      if($bit_num || $i==$c-1)
        @$low2chinses = $low2chinses.$e[$c-$i-1];
    }
    for($j=$len_pointdigit; $j>=1; $j--) {  //处理小数部分
      $point_num = substr($num, strlen($num)-$j, 1); //逐字读取 左->右
      if($point_num != 0)
        @$low2chinses = $low2chinses.$d[$point_num].$p[$j-1];
      //  if(substr($num, strlen($num)-2, 1)==0 && substr($num, strlen($num)-1, 1)==0) //小数点后两位都是0
    }
    $chinses = str_split($low2chinses,2); //字符串转换成数组
    //print_r($chinses);
    for($x=sizeof($chinses)-1;$x>=0;$x--) {     //过滤无效的信息
      if($inwan==0&&$chinses[$x]==$e[4]) {    //过滤重复的"万"
        $final[$y++] = $chinses[$x];
        $inwan=1;
      }
      if($inyi==0&&$chinses[$x]==$e[8]) {     //过滤重复的"亿"
        $final[$y++] = $chinses[$x];
        $inyi=1;
        $inwan=0;
      }
      if($chinses[$x]!=$e[4]&&$chinses[$x]!=$e[8]) //进行整理,将最后的值赋予$final数组
        $final[$y++] = $chinses[$x];
    }
    $newstring=(array_reverse($final)); //$final为倒数组，$newstring为正常可以使用的数组
    $nstring=join($newstring); //数组变成字符串
    if(substr($num,-2,1)==0 && substr($num,-1)<>0) {    //判断原金额角位为0 ? 分位不为0 ?
      $nstring=substr($nstring,0,(strlen($nstring)-4))."零".substr($nstring,-4,4); //这样加一个零字
    }
    $fen="分";
    $fj=substr_count($nstring, $fen); //如果没有查到分这个字
    return $nstring=($fj==0)?$nstring.$zheng:$nstring; //就将"整"加到后面
  }
  //确认已经打印了通知书
  public function advice_node(Request $request){
    $data = $request->post();
    $pid = $data["pid"];
    unset($data["pid"]);
    //将通知书编号保存
    if (Apply::update($data)) {
      $this->success("通知书编号保存成功");
    } else {
      $this->error("通知书编号保存失败");
    }

  }
  //收款记录
  public function search(){
    //查询所有的报名状态
    $data = array(
      "setting" => $this->getAllSetting(),
      "status" => Applytype::order("sort asc")->select(),
      "course" => Course::select(),
    );
    return view("search",$data);
  }
  //记录列表
  public function lists(){
    $arr = [
      "setting"=>$this->getAllSetting(),
    ];
    return view("lists",$arr);
  }
  //获取基本数据
  public function getAllUser(Request $request){
    $query = $request->get();

    $limit = empty($query["limit"]) ? 10 : $query["limit"];
    $page = empty($query["page"]) ? 1 : $query["page"];
    $start = ($page - 1) * $limit;
    unset($query['limit']);
    unset($query['page']);
    //创建条件变量
    $where= " and apply.status = 2";

    foreach($query as $key=> $val){
      if(!empty($val)) {
        $where .= " and ".$key." like '%".$val."%'";
      }
    }

    //sql语法
    $sql  = "select *,user.id as 'userid',apply.id as 'applyid',user.create_time as 'user_create_time',user.update_time as 'user_update_time',apply.create_time as 'apply_create_time',apply.update_time as 'apply_update_time' from user,apply where apply.userid = user.id {$where} limit {$start},{$limit}";

    $sqls = "select count(*) as c from user,apply where user.id = apply.userid".$where;
    $count = collection(Db::query($sqls))->toArray();
    $moneyCount = Db::query("select money.userid,count(money.id) as c from (user,apply) left join money on user.id = money.userid where user.id = apply.userid and apply.status = 2 group by money.userid");
    $mc = [];
    foreach($moneyCount as $v){
      $mc[$v['userid']] = $v['c'];
    }
    $data = collection(Db::query($sql))->toArray();
    foreach($data as $key=>$val){
      if(key_exists($val['userid'],$mc)) {
        $data[$key]['money_count'] = $mc[$val['userid']];
      }else{
        $data[$key]['money_count'] = 0;
      }
    }
    //组织数据
    $arr = [
      "code" =>0,
      "msg"=>'学生信息',
      "count"=>$count[0]['c'],
      "data"=>$data
    ];
    return json($arr);
  }
  //缴费详情页
  public function moneylist(Request $request){
    $arr = [
      "setting"=>$this->getAllSetting(),
      "user" => User::get($request->get("id")),
      "money" => Moneys::where("userid",$request->get("id"))->select()
    ];
    return view("moneylist",$arr);
  }
  //缴费
  public function pay(Request $request){
    if($request->post('id') == "" && $request->post('applyid') == "" && $request->post('userid') == "" && $request->post('payee') == ""){
      $this->error("参数错误");
    }else{
      $arr = $request->post();
      $arr['create_times'] = time();
      $arr['pay_number'] = mackOid();
      if(Moneys::create($arr)){
        $this->success("收款成功");
      }else{
        $this->success("收款失败");
      }
    }
  }
  //修改缴费信息
  public function update_money(Request $request){
    $money = Moneys::get($request->get("id"));
    $arr = array(
      "money"=>$money,
      "user"=>User::get($money['userid']),
      "setting"=>$this->getAllSetting(),
    );
    return view("update_money",$arr);
  }
  //保存修改
  public function save_update_money(Request $request){
    if(Moneys::update($request->post())){
      $this->success("修改成功","Money/moneylist");
    }else{
      $this->error("修改失败");
    }
  }
  //录取缴费Excel表格
  public function jfExcel()
  {
    $spreadsheet = new Spreadsheet();
    $worksheet = $spreadsheet->getActiveSheet();
    //设置工作表标题名称
    $worksheet->setTitle('缴费记录');
    //表头
    //设置单元格内容 姓名 性别 专业  缴费No  学费 学杂费 住宿费  收款人
    $worksheet->setCellValueByColumnAndRow(1, 1, '缴费记录');
    $worksheet->setCellValueByColumnAndRow(1, 2, '缴费No');
    $worksheet->setCellValueByColumnAndRow(2, 2, '姓名');
    $worksheet->setCellValueByColumnAndRow(3, 2, '性别');
    $worksheet->setCellValueByColumnAndRow(4, 2, '身份证号');
    $worksheet->setCellValueByColumnAndRow(5, 2, '专业');
    $worksheet->setCellValueByColumnAndRow(6, 2, '学费');
    $worksheet->setCellValueByColumnAndRow(7, 2, '学杂费');
    $worksheet->setCellValueByColumnAndRow(8, 2, '住宿费');
    $worksheet->setCellValueByColumnAndRow(9, 2, '缴费方式');
    $worksheet->setCellValueByColumnAndRow(10, 2, '缴费时间');
    $worksheet->setCellValueByColumnAndRow(11, 2, '收款人');
    //合并单元格
    $worksheet->mergeCells('A1:K1');

    $styleArray = [
      'font' => [
        'bold' => true
      ],
      'alignment' => [
        'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
      ],
    ];
    //设置单元格样式
    $worksheet->getStyle('A1')->applyFromArray($styleArray)->getFont()->setSize(20);
    $worksheet->getStyle('A2:J2')->applyFromArray($styleArray)->getFont()->setSize(14);
    $spreadsheet->getActiveSheet()->getColumnDimension('A')->setWidth(22);
    $spreadsheet->getActiveSheet()->getColumnDimension('B')->setWidth(20);
    $spreadsheet->getActiveSheet()->getColumnDimension('C')->setWidth(8);
    $spreadsheet->getActiveSheet()->getColumnDimension('D')->setWidth(20);
    $spreadsheet->getActiveSheet()->getColumnDimension('E')->setWidth(20);
    $spreadsheet->getActiveSheet()->getColumnDimension('F')->setWidth(10);
    $spreadsheet->getActiveSheet()->getColumnDimension('G')->setWidth(10);
    $spreadsheet->getActiveSheet()->getColumnDimension('H')->setWidth(10);
    $spreadsheet->getActiveSheet()->getColumnDimension('I')->setWidth(15);
    $spreadsheet->getActiveSheet()->getColumnDimension('J')->setWidth(18);
    $spreadsheet->getActiveSheet()->getColumnDimension('K')->setWidth(10);

    //查询所有录取信息
    $list = \think\Db::query("select user.name,user.sex,user.idcard,apply.major,money.* from money left join (apply,user) on money.userid = apply.userid where apply.userid = user.id;");

    $len = count($list);
    $j = 0;
    for ($i = 0; $i < $len; $i++) {
      $j = $i + 3; //从表格第3行开始
      $worksheet->setCellValueByColumnAndRow(1, $j, $list[$i]['pay_number']);
      $worksheet->setCellValueByColumnAndRow(2, $j, $list[$i]['name']);
      if ($list[$i]['sex']) $sex = "男"; else $sex = "女";
      $worksheet->setCellValueByColumnAndRow(3, $j, $sex);
      $worksheet->setCellValueByColumnAndRow(4, $j, $list[$i]['idcard'] . "\t");
      $worksheet->setCellValueByColumnAndRow(5, $j, $list[$i]['major']);
      $worksheet->setCellValueByColumnAndRow(6, $j, $list[$i]['money_xf']);
      $worksheet->setCellValueByColumnAndRow(7, $j, $list[$i]['money_xzf']);
      $worksheet->setCellValueByColumnAndRow(8, $j, $list[$i]['money_zsf']);
      $worksheet->setCellValueByColumnAndRow(9, $j, $list[$i]['pay_type']);
      $worksheet->setCellValueByColumnAndRow(10, $j, date('Y-m-d H:i:s',$list[$i]['create_times']));
      $worksheet->setCellValueByColumnAndRow(11, $j, $list[$i]['payee']);

    }

    $styleArrayBody = [
      'borders' => [
        'allBorders' => [
          'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
          'color' => ['argb' => '666666'],
        ],
      ],
      'alignment' => [
        'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
      ],
    ];
    $total_jzInfo = $len + 2;
    //添加所有边框/居中
    $worksheet->getStyle('A1:K' . $total_jzInfo)->applyFromArray($styleArrayBody);


    $filename = '缴费记录' . date("Y-m-d(His)") . '.xlsx';
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="' . $filename . '"');
    header('Cache-Control: max-age=0');

    $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
    $writer->save('php://output');
  }
  //删除
  public function del(Request $request){
    if(Moneys::destroy($request->post("id"))){
      $this->success("删除成功");
    }else{
      $this->error("删除失败");
    }
  }
}